package com.huaxin.hxcloud.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.AllOrgDTO;
import com.huaxin.common.Entity.AreaOrg;
import com.huaxin.common.Entity.AreaOrgDTO;
import com.huaxin.common.Entity.Org;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.tts.Constant;
import com.huaxin.hxcloud.R;
import com.huaxindata.im.main.manager.UserManager;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/9/22.
 */
public class AreaSelectActivity extends BaseActivity {


    @BindView(R.id.more)
    ImageView    more;
    @BindView(R.id.toolbar)
    Toolbar      toolbar;
    @BindView(R.id.current_area)
    TextView     currentArea;
    @BindView(R.id.task_area_grid)
    RecyclerView taskAreaGrid;
    @BindView(R.id.all_area_list)
    RecyclerView allAreaList;
    @BindView(R.id.ll_area)
    LinearLayout ll_area;

    private List<Org>     allAreaData = new ArrayList<>();
    public  List<AreaOrg> areaOrgData = new ArrayList<>();
    AreaAdapter areaAdapter;
    OrgAdapter  allAdapter;
    private Org      curOrg;
    private View     emptyView;
    private TextView tvTip;
    //保存选择的区域位置
    private int      prePosition;

    public static void start(Activity context, Org curOrg) {
        Intent intent = new Intent(context, AreaSelectActivity.class);
        intent.putExtra(Constants.IK_ORG, curOrg);
        context.startActivityForResult(intent, Constants.RET_SELECT_ORG);
    }

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        if (extras.containsKey(Constants.IK_ORG)) {
            curOrg = extras.getParcelable(Constants.IK_ORG);
        } else {
            finish();
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_station_area_select;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void initView() {
        setSupportActionBar(toolbar);
        toolbar.setTitle("组织切换");
        allAdapter = new OrgAdapter(R.layout.item_area_all, allAreaData);
        areaAdapter = new AreaAdapter(R.layout.item_area_task, areaOrgData);
        taskAreaGrid.setAdapter(areaAdapter);
        taskAreaGrid.setLayoutManager(new GridLayoutManager(this, 3));


        //碧水源 根据区域获取站点
        if (Constant.BSYorgCodeFirst.equals(UserManager.getFirstOrgCode())) {
            ll_area.setVisibility(View.VISIBLE);
        } else {
            ll_area.setVisibility(View.GONE);
        }
        allAreaList.setAdapter(allAdapter);
        allAreaList.setLayoutManager(new LinearLayoutManager(this));
        if (curOrg != null) {
            currentArea.setText(curOrg.getOrgName());
        }

        //无站点 空布局
        emptyView = LayoutInflater.from(this).inflate(R.layout.item_empty_face_top, (ViewGroup) allAreaList.getParent(), false);
        tvTip = (TextView) emptyView.findViewById(R.id.tv_tip);
        tvTip.setText("暂无组织列表!");

        allAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                Intent intent = new Intent();
                intent.putExtra(Constants.IK_ORG, allAreaData.get(position));
                setResult(RESULT_OK, intent);
                finish();
            }
        });

        areaAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                //区域选择查看对应的站点列表
                AreaOrg areaOrg = areaOrgData.get(position);
                AreaOrg preAreaOrg = areaOrgData.get(prePosition);
                preAreaOrg.setCheck(false);
                areaOrg.setCheck(true);
                areaAdapter.notifyDataSetChanged();
                prePosition = position;

                List<Org> orgArr = areaOrg.getOrgArr();
                allAreaData.clear();
                allAreaData.addAll(orgArr);
                allAdapter.setNewData(orgArr);


            }
        });
    }

    /**
     * 碧水源获取不同区域站点
     */
    private void ApiRequestData1() {
        updateLoadStatus(LOADING);
        Call<AreaOrgDTO> call = HxTransmitRequestHelper.getRequestApi().findAllOrgList1();
        autoClose(call);
        call.enqueue(new Callback<AreaOrgDTO>() {
            @Override
            public void onResponse(Call<AreaOrgDTO> call, Response<AreaOrgDTO> response) {
                AreaOrgDTO areaOrgDTO = response.body();
                if (response.isSuccessful() && areaOrgDTO != null) {
                    updateLoadStatus(LOAD_SUCCESS);
                    List<AreaOrg> areaOrgs = areaOrgDTO.getData();
                    if (areaOrgs != null && areaOrgs.size() > 0) {
                        //默认显示第一个区域站点
                        AreaOrg areaOrg = areaOrgs.get(0);
                        areaOrg.setCheck(true);
                        prePosition = 0;
                        areaOrgData.addAll(areaOrgs);
                        areaAdapter.setNewData(areaOrgs);
                        List<Org> orgArr = areaOrg.getOrgArr();
                        allAreaData.clear();
                        allAreaData.addAll(orgArr);
                        allAdapter.setNewData(orgArr);
                    } else {
                        taskAreaGrid.setVisibility(View.GONE);
                        allAdapter.setEmptyView(emptyView);
                    }

                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<AreaOrgDTO> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
            }
        });
    }

    /**
     * 无区域选择
     *
     * @param status
     */
    public void ApiRequestData(int status) {
        updateLoadStatus(status);
        Call<AllOrgDTO> call = HxTransmitRequestHelper.getRequestApi().findAllOrgList();
        autoClose(call);
        call.enqueue(new Callback<AllOrgDTO>() {
            @Override
            public void onResponse(Call<AllOrgDTO> call, Response<AllOrgDTO> response) {
                AllOrgDTO allOrgDTO = response.body();
                if (response.isSuccessful()) {
                    updateLoadStatus(LOAD_SUCCESS);
                    if (allOrgDTO != null && allOrgDTO.isSuccessful()) {
                        allAreaData.clear();
                        if (allOrgDTO.getOrgList() == null || allOrgDTO.getOrgList().isEmpty()) {
                            allAdapter.setEmptyView(emptyView);
                        } else {
                            allAreaData.addAll(allOrgDTO.getOrgList());
                            allAdapter.setNewData(allOrgDTO.getOrgList());
                        }
                    } else {
                        updateLoadStatus(LOAD_ERROR);
                    }
                } else {
                    updateLoadStatus(LOAD_ERROR);
                }
            }

            @Override
            public void onFailure(Call<AllOrgDTO> call, Throwable t) {
                updateLoadStatus(LOAD_FAILURE);
            }
        });

    }


    @Override
    public void requestData() {
        //碧水源增加区域分类查询站点
        if (Constant.BSYorgCodeFirst.equals(UserManager.getFirstOrgCode())) {
            ApiRequestData1();
        } else {
            ApiRequestData(LOADING);
        }
    }

    class AreaAdapter extends BaseQuickAdapter<AreaOrg, BaseViewHolder> {

        public AreaAdapter(int layoutResId, @Nullable List<AreaOrg> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, AreaOrg areaOrg) {
            TextView area = baseViewHolder.getView(R.id.area);
            loadText(area, areaOrg.getAreaName());
            if (areaOrg.isCheck) {
                area.setTextColor(getResources().getColor(R.color.text_color_f));
            } else {
                area.setTextColor(getResources().getColor(R.color.text_color_2));
            }
        }

    }

    class OrgAdapter extends BaseQuickAdapter<Org, BaseViewHolder> {

        public OrgAdapter(int layoutResId, @Nullable List<Org> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder baseViewHolder, Org org) {
            TextView area = baseViewHolder.getView(R.id.area);
            TextView address = baseViewHolder.getView(R.id.address);
            loadText(area, org.getOrgName());
            loadText(address, org.getAddress(), org.getRegion());
        }
    }


}
